package nciae.db.controller;

import lombok.extern.slf4j.Slf4j;
import nciae.db.common.CommonResult;
import nciae.db.entity.User;
import nciae.db.service.UserService;
import nciae.db.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping
    public CommonResult login(@RequestBody User user){
        log.info("员工登录：{}",user);
        User e=userService.login(user);

        //登录成功，生成令牌，下发令牌
        if (e!=null){
            Map<String, Object> claims=new HashMap<>();
            claims.put("id",user.getId());
            claims.put("userName",user.getUserName());
            claims.put("realName",user.getRealName());
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前登录的员工信息
            CommonResult<String> rs=new CommonResult<>();
            rs.setCode(0);
            rs.setMsg("登录成功");
            rs.setData(jwt);
            return rs;
        }

        //登陆失败，返回错误信息
        CommonResult rs=new CommonResult();
        rs.setCode(-1);
        rs.setMsg("用户名或密码错误");
        return rs;
    }
}
